// pages/scan/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: '',
    urlObj: {},
    bleName: '',
    mac: '',
    resourceDataList: wx.getStorageSync('resourceDataList'),
    deviceList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.showLoading({
      title: this.$t('加载中')
    })
    console.log("options: ", options);
    if (wx.getStorageSync('qrCodeUrl')) {
      this.bluetooth = new BluetoothSDK({
        uuid_service: "0000FFE0-0000-1000-8000-00805F9B34FB"
      })
      this.url = wx.getStorageSync('qrCodeUrl')
      this.handleUrlParams(this.url)
      return
    }
    if (options.hasOwnProperty('q') && options.q) {
      // 通过下面这步解码，可以拿到url的值
      this.url = decodeURIComponent(options.q)
      wx.setStorageSync('qrCodeUrl', this.url)
      // 将url存到本地
      if (!wx.getStorageSync('userInfo') && this.url.indexOf('apitype') == -1) {
        wx.redirectTo({
          url: `/pages/login/index`
        })
      } else {
        this.bluetooth = new BluetoothSDK({
          uuid_service: "0000FFE0-0000-1000-8000-00805F9B34FB"
        })
        this.handleUrlParams(this.url)
      }
    }
  },

  // 从二维码中获取参数
  getParamsByScanCode(url) {
    return new Promise((resolve, reject) => {
      let obj = {}
      let mac = ''
      let ble = ''
      let str = url.slice(url.indexOf('?') + 1)
      if (str.indexOf('&') == -1) {
        let arr = str.split('=')
        if (arr[0].indexOf('g') != -1) {
          obj['mac'] = arr[1]
          obj['type'] = '4g'
        } else if (arr[0].indexOf('b') != -1) {
          if (arr[1].length > 12) {
            mac = arr[1].substr(0, 12)
            ble = arr[1].substr(12, 12)
          }
          obj['mac'] = mac
          obj['bleName'] = 'M2' + ble
          obj['type'] = 'ble'
        }
      } else {
        let paramsArr = str.split('&')
        paramsArr.forEach(item => {
          let arr = item.split('=')
          if (arr[0].indexOf('g') != -1) {
            obj['mac'] = arr[1]
            obj['type'] = '4g'
          } else if (arr[0].indexOf('b') != -1) {
            if (arr[1].length > 12) {
              mac = arr[1].substr(0, 12)
              ble = arr[1].substr(12, 12)
            }
            obj['mac'] = mac
            obj['bleName'] = 'M2' + ble
            obj['type'] = 'ble'
          } else if (arr[0].indexOf('deviceModel') != -1) {
            obj['deviceModel'] = arr[1]
          } else if (arr[0].indexOf('apitype') != -1) {
            obj[arr[0]] = arr[1]
          }
        })
      }
      resolve(obj)
    })
  },

  async handleUrlParams(url) {
    // 对url中携带的参数提取处理
    this.urlObj = await this.getParamsByScanCode(url)
    wx.removeStorageSync('qrCodeUrl')
    console.log("this.urlObj: ", this.urlObj)
    // 判断4g还是蓝牙
    if (this.urlObj.type == '4g') {
      this.urlObj['deviceModel'] = await this.getDeviceModelByMac()
      // 走4g下料页
      this.handleNetDye()
      return
    }
    if (this.urlObj.type == 'ble') {
      this.urlObj['deviceModel'] = await this.getDeviceModelByMac()
      // 走蓝牙下料页
      this.handleBLEDye()
      return
    }
    // 顾客浏览用
    this.handleCustomerView()
  },
  async handleCustomerView() {
    let params = {
      ac: 'get_rgj_formula_type_list_new',
      parentid: '-1',
      language: 0,
      apitype: this.urlObj.apitype,
      ...this.$generateRequestParams({
        devicemodelid: this.urlObj.deviceModel,
      }, false)
    }
    console.log(params)
    const res = await this.$api.deviceRgjRequest(params)
    console.log("res: ", res)
    if (res.code == 0 && res.data.dataList.length > 0) {
      wx.hideLoading()
      wx.setStorageSync('devicesTypeData', res.data.dataList)
      wx.redirectTo({
        url: `/pages-color/color_series/mlp_page/color_mode?deviceModelId=${this.urlObj.deviceModel}&apitype=${this.urlObj.apitype}`
      })
    }
  },
  // 通过mac获取deviceModel
  getDeviceModelByMac() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.$apiUrl + '/DeviceModel/getDeviceModelByMac',
        data: {
          mac: this.urlObj.mac
        },
        method: 'GET',
        success: res => {
          console.log("res: ", res.data.data);
          resolve(res.data.data)
        }
      })
    })
  },
  // 走4g下料页
  async handleNetDye() {
    wx.setStorageSync('4gMac', this.urlObj.mac)
    let params = {
      ac: 'get_rgj_formula_type_list_new',
      parentid: '-1',
      language: 0,
      ...this.$generateRequestParams({
        devicemodelid: this.urlObj.deviceModel,
      }, false)
    }
    console.log(params)
    const res = await this.$api.deviceRgjRequest(params)
    console.log("res: ", res)
    if (res.code == 0 && res.data.dataList.length > 0) {
      wx.hideLoading()
      wx.setStorageSync('devicesTypeData', res.data.dataList)
      wx.redirectTo({
        url: `/pages-color/color_series/mlp_page/color_mode?deviceModelId=${this.urlObj.deviceModel}`
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})